package com.one.blocks.rbac.manager;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.alicp.jetcache.anno.CreateCache;
import com.one.blocks.mvc.manager.AbstractBatchManager;
import com.one.blocks.rbac.constant.RbacConstant.OrgCache;
import com.one.blocks.rbac.controller.valid.AllocatedDataValidateManager;
import com.one.blocks.rbac.domain.SysRoleOrg;
import com.one.blocks.rbac.enums.CacheEventEnum;
import com.one.blocks.rbac.listener.CacheClearHandler;
import com.one.blocks.rbac.mapper.SysRoleOrgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * @author <a href="mailto:idler41@163.con">idler41</a> created on 2022-05-06 10:54:42
 */
@Service
public class SysRoleOrgManager extends AbstractBatchManager<SysRoleOrgMapper, SysRoleOrg> implements AllocatedDataValidateManager<Integer>, CacheClearHandler {

    @CreateCache(area = OrgCache.AREA, name = OrgCache.ROLE_ID, cacheType = CacheType.BOTH)
    private Cache<String, Integer> orgCache;

    @Autowired
    public SysRoleOrgManager(SysRoleOrgMapper mapper) {
        super(mapper);
    }

    @CacheInvalidate(area = OrgCache.AREA, name = OrgCache.ROLE_ID, key = "#roleId")
    @Transactional(rollbackFor = Exception.class)
    public boolean grant(Integer roleId, List<SysRoleOrg> sysRoleOrgList) {
        mapper.deleteByRoleId(roleId);
        insertBatch(sysRoleOrgList);
        return true;
    }

    @Cached(area = OrgCache.AREA, name = OrgCache.ROLE_ID, key = "#roleId", cacheType = CacheType.BOTH)
    public List<Integer> selectOrgByRoleId(Integer roleId) {
        return mapper.selectByRoleId(roleId);
    }

    @Override
    public CacheEventEnum[] support() {
        return new CacheEventEnum[]{CacheEventEnum.CLEAR_ORG_ROLE};
    }

    @Override
    public void clearCache(CacheEventEnum cacheEventEnum) {
        if (cacheEventEnum == CacheEventEnum.CLEAR_ORG_ROLE) {
            Set<Integer> roleIdSet = mapper.selectAllRoleId();
            for (Integer roleId : roleIdSet) {
                orgCache.remove(OrgCache.AREA + OrgCache.ROLE_ID + roleId);
            }
        }
    }

    public Integer[] existsDataByKeys(Integer... orgIds) {
        return mapper.selectByOrgId(orgIds);
    }
}